import flash.display.Sprite;
import flash.display.Shape;
import flash.geom.Matrix;

import neash.Timer;

class Clock extends Sprite
{
   var mCx:Float;
   var mCy:Float;
   var mRad:Float;

   var mMinuteHand:Shape;
   var mSecondHand:Shape;
   var mHourHand:Shape;

   public function new(inCx:Float, inCy:Float, inRad:Float)
   {
      super();

      flash.Lib.current.addChild(this);

      mCx = inCx;
      mCy = inCy;
      mRad = inRad;

      var gfx = graphics;
      for(i in 0...12)
      {
          gfx.beginFill(0x603030);
          gfx.lineStyle(0x000000);
          var theta = i * Math.PI * 2.0 / 12.0;
          var cos1 = Math.cos(theta-0.01);
          var sin1 = Math.sin(theta-0.01);
          var cos2 = Math.cos(theta+0.01);
          var sin2 = Math.sin(theta+0.01);

          gfx.moveTo( mCx + cos1*mRad,     mCy + sin1*mRad );
          gfx.lineTo( mCx + cos2*mRad,     mCy + sin2*mRad );
          gfx.lineTo( mCx + cos2*mRad*1.1, mCy + sin2*mRad*1.1 );
          gfx.lineTo( mCx + cos1*mRad*1.1, mCy + sin1*mRad*1.1 );
          gfx.lineTo( mCx + cos1*mRad,     mCy + sin1*mRad );
          gfx.endFill();
      }

      mSecondHand = CreateHand(mRad*0.02,mRad);
      mMinuteHand = CreateHand(mRad*0.05,mRad*0.75);
      mHourHand = CreateHand(mRad*0.1,mRad*0.5);

      var timer = new Timer(1000);
      var me = this;
      timer.run = function() { me.SetHandPositions(); }
      SetHandPositions();
   }

   function SetHandPositions()
   {
      var date = Date.now();

      var hour = date.getHours() % 12;
      var minute = date.getMinutes();
      var seconds = date.getSeconds();

      mSecondHand.rotation = seconds *360/60;
      mMinuteHand.rotation = (minute + seconds/60.0)  * 360/60;
      mHourHand.rotation =   (hour + minute/60.0 + seconds/3600.0) * 360/12;
   }

   function CreateHand(inWidth:Float, inLength:Float) : Shape
   {
      var result = new Shape();
      addChild(result);

      var gfx = result.graphics;

      gfx.beginFill(0x303060);
      gfx.moveTo(0,0);
      gfx.lineTo(-inWidth/2,-inWidth);
      gfx.lineTo(0,-inLength);
      gfx.lineTo(inWidth/2,-inWidth);
      gfx.lineTo(0,0);

      result.x = mCx;
      result.y = mCy;

      return result;
   }

   static public function main()
   {
#if js
     haxe.Firebug.redirectTraces();
#end
      neash.Lib.Init("Clock",640,480); 
      neash.Lib.SetBackgroundColour(0xffffff); 

      new Clock(320,240,200);

      neash.Lib.Run(); 
   }
}

